﻿using System.Data.Linq.Mapping;
using System.Linq;

namespace TruyenTranhCrawler.Data
{
    [Table]
    public class Author : BaseObject
    {
        [Column(IsPrimaryKey = true, IsDbGenerated = true)]
        public int ID { get; set; }

        [Column]
        public string FullName { get; set; }
        [Column]
        public string SortName { get; set; }    //to search
        [Column]
        public string SafeName { get; set; }    //to display url

        /// <summary>
        /// Insert if not existed, then return Id
        /// </summary>
        /// <returns></returns>
        public static int InsertSkipExisted(string fullname)
        {
            if (string.IsNullOrEmpty(fullname)) return 0;
            var safeName = GetSafeName(fullname);
            var sortname = GetSortNameFromSafeName(safeName);
            using (var context = new CmsDataContext())
            {
                context.ExecuteCommand("if not exists(select * from Author where SortName={0}) insert into Author(SortName,SafeName,FullName) values({0},{1},{2})", sortname, safeName, fullname);
                var auth = context.Authors.FirstOrDefault(x => x.SafeName == safeName);
                return auth != null ? auth.ID : 0;
            }
        }
    }
}
